import { Component, forwardRef, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';

import { defalutImg } from 'src/app/comm';
import { LoveComponentsService } from '../love-components.service';

@Component({
  selector: 'app-upload-imgs',
  templateUrl: './upload-imgs.component.html',
  styleUrls: ['./upload-imgs.component.scss']
})
export class UploadImgsComponent implements OnInit {
  @Input() imgLists: string[] = [];
  @Input() limit: number = 1;
  @Output() imgChange = new EventEmitter();
  @Output() deleteChange = new EventEmitter();

  fallback: string = defalutImg;
  uploadLoading: boolean = false;

  constructor(
    private message: NzMessageService,
    private services: LoveComponentsService
  ) { }

  ngOnInit(): void {
  }

  // upload Change
  handleChange(ev: any) {
    const { originFileObj }: any = ev?.file;
    this.uploadInterface(originFileObj);
  }

  // delete img
  deleteImg(index: number) {
    this.deleteChange.emit(this.imgLists[index]);
    this.imgLists.splice(index, 1);
    this.imgChange.emit(this.imgLists);
  }

  async uploadInterface(file: any) {
    if (!file || this.uploadLoading) {
      return
    }
    let imgData: string = '';
    this.uploadLoading = true;
    const res: any = await this.services.uploadFileData(file)
    this.uploadLoading = false;

    if (res.code == 0) {
      this.message.success('图片上传成功');
      this.imgLists.push(res.data);
      this.imgChange.emit(this.imgLists);
    } else {
      this.message.error(res.message);
    }
  }
}
